package com.woniu.interceptor;

import com.woniu.annotation.CheckPermission;
import com.woniu.util.JwtUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zgc  2024/6/26
 */
public class PermissionInterceptor implements HandlerInterceptor {

    @Resource
    JwtUtil jwtUtil;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // handler代表正要执行的对象
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            // 判断是否有指定的权限
            boolean f = method.hasMethodAnnotation(CheckPermission.class);
            if(f){
                // 1: 得到注解上的权限值
                CheckPermission checkPermission = method.getMethodAnnotation(CheckPermission.class);
                String value = checkPermission.value();
                System.out.println(method.getMethod().getName()+":这个方法需要的权限是:"+value);

                // 2：判断当前用户是否有这个权限
                // 得到用户名
                String token = request.getHeader("token");
                String userName = jwtUtil.parseToken(token);
                // 因为登录的时候，就缓存了权限数据，所以我们只要从redis里面取权限数据
                Boolean b = stringRedisTemplate.opsForSet().isMember("permission:" + userName, value);
                if(b){
                    return true;
                }else {
                    throw new RuntimeException("对不起,您的权限不足！当前需要：<"+value+">权限!");
                }
            }else {
                return true;
            }
        }
        return true;
    }
}
